<template>
  <div class="home">
    <van-search
     v-model="search_key"
     @keydown.enter="getResults"
     @focus="is_focus=true"
     shape="round"
     background="#ffd000"
     placeholder="请输入搜索关键词"/>
     <div v-if="show_history">
      <search-history @search="onSearch"/>
     </div>
     <div v-if="show_suggestion">
        <search-suggestion :suggestions="suggestions" :search_key="search_key" @search="onSearch"/>
     </div>
     <div v-if="show_results">
       <search-result :results="results"/>
     </div>

  </div>
</template>

<script>
import SearchHistory from '../components/SearchHistory.vue'
import SearchSuggestion from '../components/SearchSuggestion.vue'
import SearchResult from '../components/SearchResult.vue'
import { search } from '../api/dream'
import debounce from 'lodash.debounce'
export default {
  name: 'Dream',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      search_key: '',
      name: '测算大师',
      persons: [{ name: '李世民', age: 18 }, { name: '李建成', age: 17 }],
      results: [],
      suggestions: [],
      show_history: true,
      show_results: false,
      show_suggestion: false,
      is_focus: false
    }
  },
  watch: {
    search_key: debounce(async function (newVal) {
      if (newVal === '') {
        this.suggestions = []
        this.show_suggestion = false
        this.show_results = false
        this.show_history = true
        return
      }
      const { data: { result } } = await search({ q: newVal })
      console.log(result)
      this.suggestions = result.map((item) => item.title)
      if (this.is_focus === true && newVal !== '') {
        this.show_history = false
        this.show_results = false
        this.show_suggestion = true
      }
    }, 200)
  },
  methods: {
    onSearch (item) {
      this.show_history = false
      this.show_suggestion = false
      this.is_focus = false
      this.search_key = item
      this.getResults()
    },
    async getResults () {
      const { data } = await search({ q: this.search_key })
      this.results = data.result
      this.suggestions = []
      this.show_results = true
    }
  }
}
</script>

<style lang = "less" scoped>
  .home{
    height: 100vh;
    width:100vw;
    background: rgb(253, 249, 249);
    /deep/.van-search{
        height: 200px;
        .van-search__content{
          height: 130px;
          align-items: center;
          font-size: 28px;
          .van-icon-clear{
            font-size: 0.95rem;
          }
          .van-field__left-icon .van-icon, .van-field__right-icon .van-icon{
            font-size: 0.95rem;
          }
          .van-cell{
            line-height: 130px;
            font-size:  0.95rem;
          }
        }
    }
  }
</style>
